package com.qiangesoft.miniapp.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.qiangesoft.miniapp.entity.SysUser;
import com.qiangesoft.miniapp.exception.CommonExceptionEnum;
import com.qiangesoft.miniapp.exception.ServiceException;
import com.qiangesoft.miniapp.pojo.dto.UserLoginDTO;
import com.qiangesoft.miniapp.pojo.vo.UserLoginVO;
import com.qiangesoft.miniapp.service.ISysUserService;
import com.qiangesoft.miniapp.util.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

/**
 * 认证控制器
 *
 * @author qiangesoft
 * @date 2024-07-17
 */
@Api(tags = "认证管理")
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/auth")
public class AuthController {

    private final WxMaService wxMaService;

    private final ISysUserService sysUserService;

    @ApiOperation("获取微信官方用户信息")
    @PostMapping(value = "/wxSession")
    public ResultVO<WxMaJscode2SessionResult> wxSession(@Valid @NotBlank(message = "微信code不能为空") String code) throws WxErrorException {
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        return ResultVO.success(sessionInfo);
    }

    @ApiOperation("微信授权登录")
    @PostMapping(value = "/wxLogin")
    public ResultVO<String> wxLogin(@Validated(UserLoginDTO.AuthLogin.class) @RequestBody UserLoginDTO userLoginDTO) {
        String wxOpenId = userLoginDTO.getWxOpenId();
        SysUser sysUser = sysUserService.selectByWxOpenId(wxOpenId);
        if (null == sysUser) {
            sysUser = sysUserService.bind(wxOpenId);
        }

        if (sysUser == null) {
            throw new ServiceException(CommonExceptionEnum.BIND_FAIL);
        }

        StpUtil.login(sysUser.getId());

        return ResultVO.success(StpUtil.getTokenValue());
    }

    @ApiOperation("获取用户信息")
    @GetMapping(value = "/userInfo")
    public ResultVO<UserLoginVO> userInfo() {
        long userId = StpUtil.getLoginIdAsLong();
        SysUser sysUser = sysUserService.getById(userId);
        if (null == sysUser) {
            return ResultVO.fail("用户不存在");
        }

        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtil.copyProperties(sysUser, userLoginVO);
        userLoginVO.setToken(StpUtil.getTokenValue());

        return ResultVO.success(userLoginVO);
    }

    @ApiOperation("退出登录")
    @PostMapping(value = "/logout")
    public ResultVO logout() {
        StpUtil.logout();
        return ResultVO.success();
    }

}
